package com.noahsloan.nutils.streams;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Iterator;

/**
 * Writes to a series of filenames, advancing to the next filename when close is
 * called.
 * 
 * @author noah
 * 
 */
public class FileOutputStreamSeries extends OutputStreamSeries {

	public FileOutputStreamSeries(final String basename) {
		this(new FilenameGenerator(basename));
	}

	public FileOutputStreamSeries(final FilenameGenerator names) {
		super(names);
	}

	/**
	 * Generates file output streams of the pattern 'basename-count'. Subclasses
	 * can override {@link #next()} to change the naming pattern.
	 * 
	 * @author noah
	 * 
	 */
	public static class FilenameGenerator implements Iterator<OutputStream> {

		protected String basename;

		protected int count;

		public FilenameGenerator(final String basename) {
			super();
			this.basename = basename;
		}

		public boolean hasNext() {
			return true;
		}

		public synchronized OutputStream next() {
			try {
				return new FileOutputStream(basename + '-' + count++);
			} catch (FileNotFoundException e) {
				return new IOExceptionOutputStream(e);
			}
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}
	}
}
